<template>
  <div class="notes-list">
    <div class="header">
      <h1>我的笔记</h1>
      <div class="header-actions">
        <el-button @click="openSettings" :icon="Setting" circle />
        <el-button type="primary" @click="createNote" :size="isMobile ? 'small' : 'default'">
          <el-icon><Plus /></el-icon>
          <span v-if="!isMobile">新建笔记</span>
        </el-button>
      </div>
    </div>

    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索笔记..."
        clearable
        @input="handleSearch"
        @clear="handleClearSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 加载状态 -->
    <div v-if="notesStore.loading" class="loading-container">
      <el-icon class="is-loading" size="32"><Loading /></el-icon>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <el-alert
      v-else-if="notesStore.error"
      :title="notesStore.error"
      type="error"
      :closable="false"
      style="margin: 20px;"
    />

    <!-- 空状态 -->
    <div v-else-if="notesStore.notes.length === 0" class="empty-state">
      <el-empty description="还没有笔记">
        <el-button type="primary" @click="createNote">创建第一篇笔记</el-button>
      </el-empty>
    </div>

    <!-- 笔记列表 -->
    <div v-else class="notes-grid">
      <el-card
        v-for="note in notesStore.filteredNotes"
        :key="note._id"
        class="note-card"
        @click="openNote(note._id)"
        shadow="hover"
      >
        <div class="note-header">
          <div class="note-title">{{ note.title || '无标题' }}</div>
          <el-dropdown @command="handleNoteAction" trigger="click">
            <el-button type="text" :icon="MoreFilled" size="small" @click.stop />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="{ action: 'edit', id: note._id }">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-dropdown-item>
                <el-dropdown-item :command="{ action: 'delete', id: note._id }">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        
        <div class="note-preview" v-html="getPreview(note.content)"></div>
        
        <div class="note-tags" v-if="note.tags && note.tags.length > 0">
          <el-tag
            v-for="tag in note.tags.slice(0, 3)"
            :key="tag"
            size="small"
            style="margin: 2px;"
          >
            {{ tag }}
          </el-tag>
          <el-tag v-if="note.tags.length > 3" size="small" style="margin: 2px;">
            +{{ note.tags.length - 3 }}
          </el-tag>
        </div>
        
        <div class="note-meta">
          <span class="note-date">{{ formatDate(note.updatedAt) }}</span>
          <el-icon v-if="note.isPublic" title="公开"><View /></el-icon>
        </div>
      </el-card>
    </div>

    <!-- 加载更多 -->
    <div v-if="notesStore.hasMore && !notesStore.loading" class="load-more">
      <el-button @click="loadMore" :loading="loadingMore">加载更多</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Setting,
  Search,
  Loading,
  Edit,
  Delete,
  MoreFilled,
  View
} from '@element-plus/icons-vue'
import { useNotesStore } from '../stores/notes'

const router = useRouter()
const notesStore = useNotesStore()

// 响应式状态
const searchQuery = ref('')
const loadingMore = ref(false)

// 计算属性
const isMobile = computed(() => window.innerWidth < 768)

// 生命周期
onMounted(async () => {
  await notesStore.loadNotes()
})

// 方法
const handleSearch = () => {
  if (searchQuery.value.trim()) {
    notesStore.searchNotes(searchQuery.value.trim())
  }
}

const handleClearSearch = () => {
  searchQuery.value = ''
  notesStore.clearSearch()
}

const createNote = () => {
  router.push('/editor')
}

const openSettings = () => {
  router.push('/settings')
}

const openNote = (id: string) => {
  router.push(`/editor/${id}`)
}

const loadMore = async () => {
  loadingMore.value = true
  try {
    await notesStore.loadMore()
  } finally {
    loadingMore.value = false
  }
}

const handleNoteAction = async (command: { action: string, id: string }) => {
  const { action, id } = command
  
  if (action === 'edit') {
    openNote(id)
  } else if (action === 'delete') {
    await deleteNote(id)
  }
}

const deleteNote = async (id: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这篇笔记吗？',
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const success = await notesStore.deleteNote(id)
    if (success) {
      ElMessage.success('笔记删除成功')
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    // 用户取消删除
  }
}

const getPreview = (content: string): string => {
  if (!content) return '无内容'
  
  // 移除HTML标签
  const text = content.replace(/<[^>]*>/g, '')
  return text.length > 100 ? text.substring(0, 100) + '...' : text
}

const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}
</script>

<style scoped>
.notes-list {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
  overflow-y: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header h1 {
  margin: 0;
  font-size: 28px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-bar {
  margin-bottom: 24px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
}

.loading-container p {
  margin-top: 12px;
  font-size: 14px;
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
}

.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.note-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
}

.note-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.note-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
  flex: 1;
  margin-right: 8px;
}

.note-preview {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 12px;
  min-height: 60px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.note-tags {
  margin-bottom: 12px;
  min-height: 24px;
}

.note-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
  border-top: 1px solid #f0f0f0;
  padding-top: 8px;
}

.note-date {
  flex: 1;
}

.load-more {
  display: flex;
  justify-content: center;
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notes-list {
    padding: 16px;
  }
  
  .header h1 {
    font-size: 24px;
  }
  
  .notes-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .note-card {
    margin-bottom: 8px;
  }
}

@media (max-width: 480px) {
  .notes-list {
    padding: 12px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
}
</style>